package cn.ucox.web.ms.plugin;

import cn.ucox.web.ms.polling.IFileLoader;
import com.alibaba.fastjson.JSONObject;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * FastFS文件加载器
 *
 * @author chenw
 * @create 2017-05-12 14:54
 * @email javacspring@gmail.com
 */
public class FastFSFileLoader implements IFileLoader {

    private static final Logger logger = LoggerFactory.getLogger(FastFSFileLoader.class);

    private static FastFileStorageClient storageClient;

    public FastFSFileLoader(FastFileStorageClient storageClient) {
        FastFSFileLoader.storageClient = storageClient;
    }

    @Override
    public JSONObject getFileByInterface(String url) {
        Map<String, String> params = new HashMap<>();
        params.put("fileUrl", url);
//        return HttpClientUtil.doPost(fastDFSConnectionPool.getmFastDFSConfig().getDownloadUrl(),params,"UTF-8");
        return null;
    }

    @Override
    public JSONObject getFile(String url) {
        boolean loop = true;
        JSONObject result = new JSONObject(3);
        int counter = 0;
        do {
            if (counter > 3) {
                logger.error("已尝试:{}次加载附件失败", counter);
                break;
            }
            try {
                int length = url.length();
                if (url.startsWith("/")) {
                    url = url.substring(1, length);
                }
                long start = System.currentTimeMillis();
                result = downloadSec(url);
                logger.debug("附件下载耗时:{}ms", System.currentTimeMillis() - start);
                loop = false;
            } catch (Exception ex) {
                logger.error("下载附件{}，出错:{}", url, ex.getMessage());
                counter++;
                loop = true;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (loop);
        return result;
    }

    private JSONObject downloadSec(String fileId) {

        StorePath storePath = StorePath.praseFromUrl(fileId);
        JSONObject attJson = new JSONObject(3);
        byte[] bytes = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(),
                new DownloadCallback<byte[]>() {
                    @Override
                    public byte[] recv(InputStream inputStream) throws IOException {
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        byte[] buffer = new byte[4096];
                        int n = 0;
                        while (-1 != (n = inputStream.read(buffer))) {
                            output.write(buffer, 0, n);
                        }
                        return output.toByteArray();
                    }
                });
        attJson.put("fileName", fileId.substring(fileId.lastIndexOf("/") + 1));
        attJson.put("suffix", fileId.substring(fileId.lastIndexOf(".") + 1));
        attJson.put("content", Base64Utils.encodeToString(bytes));
        return attJson;
    }
}
